from rocketmq.client import Producer, Message, SendStatus
import json


class RocketMQProducer:
    def __init__(self, group_id, namesrv_addr):
        self.producer = Producer(group_id)
        # rocketmq队列接口地址（服务器ip:port）
        self.producer.set_namesrv_addr(namesrv_addr)
        self.producer.start()

    def __del__(self):
        self.producer.shutdown()

    def produce_message(self, msg: Message):
        retmq = self.producer.send_sync(msg)
        assert retmq.status == SendStatus(0)
        print(retmq.status, retmq.msg_id, retmq.offset)
        return retmq


if __name__ == "__main__":
    gruop_id = "producerGroup"
    namesrv_addr = 'rocket-dev.bnq.in:9876'

    producer = RocketMQProducer(gruop_id,namesrv_addr)
    msg_body = {"id": "001", "name": "test_mq", "message": "abcdefg"}
    ss = json.dumps(msg_body).encode('utf-8')
    topic_name = "ship_order"
    keys = "0319193042"
    tags = "confirm"
    msg = Message(topic_name)  # topic名称
    msg.set_keys(keys)
    msg.set_tags(tags)
    msg.set_body(ss)  # message body

    retmq = producer.produce_message(msg)
    # assert retmq.status == "SendStatus.OK"
    # print(retmq.status, retmq.msg_id, retmq.offset)
